package com.rt.java.util.concurrent;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicMarkableReference;

public class AtomicMarkableReferenceDemo {
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "李四");
        map.put("age", 20);
        AMRCache amrCache = new AMRCache(map);
        System.out.println(amrCache.get("name"));
        amrCache.invalidCache();
        System.out.println(amrCache.get("name"));
    }
}

class AMRCache {
    AtomicMarkableReference<Map<String, Object>> amr = new AtomicMarkableReference<>(null, true);

    public AMRCache(Map<String, Object> cache) {
        amr.set(cache, true);
    }

    public Object get(String key) {
        boolean[] markHolder = new boolean[1];
        Map<String, Object> expectedReference = amr.get(markHolder);
        boolean expectMark = markHolder[0];
        if (expectMark) {
            return expectedReference.get(key);
        }
        Map<String, Object> newReference = new HashMap<>();
        newReference.put("name", "张三");
        newReference.put("age", 18);
        boolean newMark = true;
        do {
            expectedReference = amr.get(markHolder);
            expectMark = markHolder[0];
        } while (!amr.compareAndSet(expectedReference, newReference, expectMark, newMark));
        return newReference.get(key);
    }

    // 使缓存失效(更新boolean=false)
    public void invalidCache() {
        boolean[] markHolder = new boolean[1];
        Map<String, Object> expectedReference = null;
        do {
            expectedReference = amr.get(markHolder);
        } while (!amr.attemptMark(expectedReference, false));
    }

}